继续// Downloader module to handle HLS video downloads

// Function to download an HLS video
async function downloadHLSVideo(videoUrl, filename) {
  try {
    // For now, we'll just download the m3u8 file directly
    // In a more advanced implementation, we would process the HLS stream
    
    // Create a download using Chrome's downloads API
    chrome.downloads.download({
      url: videoUrl,
      filename: filename || getFilenameFromUrl(videoUrl),
      saveAs: true
    }, (downloadId) => {
      if (chrome.runtime.lastError) {
        console.error('Download failed:', chrome.runtime.lastError);
      } else {
        console.log('Download started with ID:', downloadId);
      }
    });
  } catch (error) {
    console.error('Error downloading HLS video:', error);
  }
}

// Function to get a filename from a URL
function getFilenameFromUrl(url) {
  try {
    const urlObj = new URL(url);
    const pathname = urlObj.pathname;
    const filename = pathname.substring(pathname.lastIndexOf('/') + 1);
    
    // If the filename doesn't have an extension or is just ".m3u8", create a better name
    if (!filename || filename === '.m3u8' || filename.endsWith('.m3u8')) {
      const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
      return `hls-video-${timestamp}.m3u8`;
    }
    
    return filename;
  } catch (error) {
    // If URL parsing fails, use a default name
    const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
    return `hls-video-${timestamp}.m3u8`;
  }
}

// Function to process and download a complete HLS stream
// This is a simplified version - a full implementation would be much more complex
async function downloadHLSStream(videoUrl, filename) {
  try {
    // Fetch the m3u8 playlist
    const response = await fetch(videoUrl);
    const playlistText = await response.text();
    
    // Parse the playlist to get the TS segments
    const segments = parseM3U8Playlist(playlistText, videoUrl);
    
    // For now, we'll just download the playlist and log the segments
    // A full implementation would download all segments and combine them
    
    console.log('HLS segments found:', segments);
    
    // Download the main playlist
    downloadHLSVideo(videoUrl, filename);
    
    // In a complete implementation, you would:
    // 1. Download all TS segments
    // 2. Combine them into a single file
    // 3. Convert to a more common format like MP4
    // 4. Handle encryption if present
    
  } catch (error) {
    console.error('Error processing HLS stream:', error);
  }
}

// Function to parse an M3U8 playlist and extract segment URLs
function parseM3U8Playlist(playlistText, baseUrl) {
  const lines = playlistText.split('\n');
  const segments = [];
  
  for (let i = 0; i < lines.length; i++) {
    const line = lines[i].trim();
    
    // Skip comments and empty lines
    if (line.startsWith('#') || line === '') {
      continue;
    }
    
    // Check if it's a relative or absolute URL
    try {
      new URL(line);
      // It's an absolute URL
      segments.push(line);
    } catch (e) {
      // It's a relative URL, resolve it against the base URL
      try {
        const resolvedUrl = new URL(line, baseUrl);
        segments.push(resolvedUrl.toString());
      } catch (e) {
        console.warn('Could not resolve URL:', line);
      }
    }
  }
  
  return segments;
}

// Enhanced function to download HLS stream with more detailed processing
async function downloadHLSStreamEnhanced(videoUrl, title) {
  try {
    console.log('Starting enhanced HLS stream download for:', videoUrl);
    
    // Create a more descriptive filename
    let filename = 'hls-stream.m3u8';
    if (title) {
      // Clean the title for use as filename
      filename = title.replace(/[^a-zA-Z0-9\s-]/g, '').replace(/\s+/g, '-').substring(0, 50) + '.m3u8';
    }
    
    // Download the playlist file
    downloadHLSVideo(videoUrl, filename);
    
    // In a more complete implementation, we would:
    // 1. Parse the main playlist
    // 2. Identify all variant streams (different resolutions)
    // 3. Choose the best quality stream
    // 4. Download the media playlist
    // 5. Extract and download all TS segments
    // 6. Combine segments into a single file
    // 7. Convert to MP4 if needed
    
    console.log('HLS stream download initiated for:', videoUrl);
  } catch (error) {
    console.error('Error in enhanced HLS stream download:', error);
  }
}

// Export functions for use in other modules
// In Manifest V3, we need to use ES modules or expose functions globally
window.HLSDownloader = {
  downloadHLSVideo,
  downloadHLSStream,
  downloadHLSStreamEnhanced
};